Container的職責在於創建、配置與組裝bean,昨天我們學到了
今日將討論使用Spring來設定資料庫連線池
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="sa"></property>
        <property name="password" value="sa"></property>
        <property name="jdbcUrl" value="jdbc:h2:mem:test"></property>
        <property name="driverClass" value="org.h2.Driver"></property>
    </bean>
</beans>
@Test
public void testDay11(){
    ApplicationContext ioc = new ClassPathXmlApplicationContext("bean11.xml");
    System.out.println("容器啟動完成....");
    DataSource ds = ioc.getBean("dataSource",DataSource.class);
    System.out.println(ds);
}
Result
在專案開發上通常會將資料庫資訊寫在外部properties檔案中。需要在spring設定檔中加入context schema
# dbconfig.properties
jdbc.user=sa
jdbc.password=sa
jdbc.jdbcUrl=jdbc:h2:mem:test
jdbc.driverClass=org.h2.Driver
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 加載外部文件   -->
    <context:property-placeholder location="classpath:dbconfig.properties"></context:property-placeholder>
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="driverClass" value="${jdbc.driverClass}"></property>
    </bean>
</beans>
Result
同上